// 验证
const { body, query, param, validationResult } = require("express-validator");

const User = require("../model/system/User");
const Article = require("../model/article");

const { validate, ValidateObjectProp } = require("../middleware/validation");
const { default: mongoose } = require("mongoose");

// 新增文章验证
exports.createArticle = validate([
  body("title").notEmpty().withMessage("标题不能为空"),
  body("description").notEmpty().withMessage("描述不能为空"),
]);
// 获取文章验证
exports.getArticleDetail = validate([
  param("id").notEmpty().withMessage("id不能为空"),
  param("id").custom(async (id) => {
    if (!mongoose.isValidObjectId(id)) {
      return Promise.reject("id格式不正确");
    }
  }),
]);

// 修改文章验证
// 校验文章是否存在
// 验证文章是否为当前登录用户
exports.checkArticle = validate([ValidateObjectProp(["param", "query"], "id")]);
exports.updateArticle = [
  async (req, res, next) => {
    const article = await Article.findById(req.params.id);
    req.article = article;
    if (!article) {
      return res.status(404).json({ message: "文章不存在" });
    }
    next();
  },
  async (req, res, next) => {
    if (req.user._id.toString() !== req.article.author.toString()) {
      return res.status(403).json({ message: "没有权限" });
    }
    next();
  },
];

// 删除文章验证
exports.deleteArticle = [
  async (req, res, next) => {
    console.log(req.params.id, "IDIDID");
    const article = await Article.findById(req.params.id);
    req.article = article;
    if (!article) {
      return res.status(404).json({ message: "文章不存在" });
    }
    next();
  },
  async (req, res, next) => {
    if (req.user._id.toString() !== req.article.author.toString()) {
      return res.status(403).json({ message: "没有权限" });
    }
    next();
  },
];
